package com.hbhmzy.call;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.WrapperListAdapter;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends Activity implements EasyPermissions.PermissionCallbacks{
    String[] params={Manifest.permission.RECORD_AUDIO};
    public static final int RECORD_AUDIO = 100;//随便赋值的一个唯一标识码
    private SharedPreferences pref;//通过SharedPreferences储存用户昵称与是否选择记住昵称
    private SharedPreferences.Editor editor;
    private CheckBox remembername;
    EditText name_edit;
    String name;

    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        checkPermission();//检查权限
        Button btn = findViewById(R.id.login);
        name_edit = findViewById(R.id.edit_name);
        remembername = findViewById(R.id.checkbox);
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        Boolean isRemember = pref.getBoolean("remember_name",false);
        if(isRemember){//如果之前勾选了记住用户名，将保存的昵称放入EditText
            name = pref.getString("name","");
            name_edit.setText(name);
            remembername.setChecked(true);
        }
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean checknet=isNetworkAvailable(LoginActivity.this);
                if(checknet){
                    String name1 = name_edit.getText().toString();
                    if(name1.length()!=11){
                        Toast.makeText(LoginActivity.this,"请输入合法的手机号",Toast.LENGTH_SHORT).show();
                    }else{
                        editor=pref.edit();
                        if(remembername.isChecked()){
                            editor.putString("name",name1);
                            editor.putBoolean("remember_name",true);
                        }else editor.clear();
                        editor.apply();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra("name",name1);
                        startActivity(intent);
                    }
                }
                else  Toast.makeText(LoginActivity.this,"您的手机网络无连接，可能无法使用",Toast.LENGTH_SHORT).show();
            }
        });
    }
    //检查有无网络连接
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }


    //按两次返回键退出
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime)>2000){
                Toast.makeText(LoginActivity.this,"再按一次退出",Toast.LENGTH_SHORT).show();
                exitTime=System.currentTimeMillis();
            }else{
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //检查是否开启权限
    @AfterPermissionGranted(RECORD_AUDIO)
    private void checkPermission() {
        if(!EasyPermissions.hasPermissions(this,params)){
            EasyPermissions.requestPermissions(this,"需要开启录音权限",RECORD_AUDIO,params);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            //这里表示拒绝权限后再点击出现的去设置对话框
            //这里需要重新设置Rationale和title，否则默认是英文格式
            //Rationale：对话框的提示内容，否则默认是英文格式
            // title：对话框的提示标题，否则默认是英文格式

            new AppSettingsDialog.Builder(this)
                    .setRationale("没有该权限，此应用程序可能无法正常工作。打开应用设置屏幕以修改应用权限")
                    .setTitle("必需权限")
                    .build()
                    .show();
        }else if (!EasyPermissions.hasPermissions(this, params)) {
            //这里响应的是除了AppSettingsDialog这个弹出框，剩下的两个弹出框被拒绝或者取消的效果
            finish();
        }

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            if (!EasyPermissions.hasPermissions(this, params)) {
                //这里响应的是AppSettingsDialog点击取消按钮的效果
                finish();
            }
        }
    }



}
